<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>任务统计</span>
              <el-button type="primary" size="small" @click="refreshData">刷新数据</el-button>
            </div>
          </template>
          <div v-loading="loading.stats">
            <el-row :gutter="20">
              <el-col :span="4">
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-title">总任务数</div>
                  <div class="stat-value">{{ taskStats.total || 0 }}</div>
                </el-card>
              </el-col>
              <el-col :span="4">
                <el-card shadow="hover" class="stat-card success">
                  <div class="stat-title">成功</div>
                  <div class="stat-value">{{ taskStats.status_counts?.success || 0 }}</div>
                </el-card>
              </el-col>
              <el-col :span="4">
                <el-card shadow="hover" class="stat-card failure">
                  <div class="stat-title">失败</div>
                  <div class="stat-value">{{ taskStats.status_counts?.failure || 0 }}</div>
                </el-card>
              </el-col>
              <el-col :span="4">
                <el-card shadow="hover" class="stat-card running">
                  <div class="stat-title">进行中</div>
                  <div class="stat-value">{{ taskStats.status_counts?.running || 0 }}</div>
                </el-card>
              </el-col>
              <el-col :span="4">
                <el-card shadow="hover" class="stat-card pending">
                  <div class="stat-title">等待中</div>
                  <div class="stat-value">{{ taskStats.status_counts?.pending || 0 }}</div>
                </el-card>
              </el-col>
              <el-col :span="4">
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-title">今日成功率</div>
                  <div class="stat-value">{{ taskStats.time_stats?.today?.success_rate || 0 }}%</div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 任务状态分布 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>任务状态分布</span>
            </div>
          </template>
          <div v-loading="loading.stats" class="chart-container">
            <div ref="statusChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 成功率趋势 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>成功率趋势</span>
            </div>
          </template>
          <div v-loading="loading.stats" class="chart-container">
            <div ref="successRateChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 任务类型统计 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>任务类型统计</span>
            </div>
          </template>
          <div v-loading="loading.stats">
            <el-table :data="taskTypeData" border style="width: 100%">
              <el-table-column prop="name" label="任务名称" min-width="200" show-overflow-tooltip />
              <el-table-column prop="count" label="执行次数" width="120" align="center" />
              <el-table-column prop="success_rate" label="成功率" width="120" align="center">
                <template #default="scope">
                  <el-progress 
                    :percentage="scope.row.success_rate" 
                    :status="getSuccessRateStatus(scope.row.success_rate)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="viewTaskResults(scope.row.name)">查看结果</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 最近执行的任务 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>最近执行的任务</span>
              <el-button type="primary" size="small" @click="viewAllResults">查看全部</el-button>
            </div>
          </template>
          <div v-loading="loading.recent">
            <el-table :data="recentTasks" border style="width: 100%">
              <el-table-column prop="task_id" label="任务ID" width="80" align="center" show-overflow-tooltip />
              <el-table-column prop="task_name" label="任务名称" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column label="状态" width="100" align="center">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)" effect="dark">
                    {{ scope.row.status_display }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="date_done" label="完成时间" width="160" align="center" show-overflow-tooltip />
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="viewTaskDetail(scope.row.id)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="recentTasksQuery.page"
                v-model:page-size="recentTasksQuery.page_size"
                :page-sizes="[10, 20, 50, 100]"
                :total="recentTasksTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleRecentTasksSizeChange"
                @current-change="handleRecentTasksPageChange"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import requestUtil, { getServerUrl } from '@/util/request'
import * as echarts from 'echarts'

// 不需要注册组件，使用完整版 echarts

const router = useRouter()
const statusChartRef = ref(null)
const successRateChartRef = ref(null)
let statusChart = null
let successRateChart = null

// 加载状态
const loading = reactive({
  stats: false,
  recent: false
})

// 数据
const taskStats = ref({})
const recentTasks = ref([])
const taskTypeData = ref([])

// 分页参数
const recentTasksQuery = reactive({
  page: 1,
  page_size: 10,
  ordering: '-date_done'
})
const recentTasksTotal = ref(0)

// 获取任务统计信息
const getTaskStats = async () => {
  loading.stats = true
  try {
    const response = await requestUtil.get('tasks/task_result/task_stats/')
    taskStats.value = response
    
    // 处理任务类型数据
    if (response.task_type_stats) {
      taskTypeData.value = Object.entries(response.task_type_stats).map(([name, data]) => ({
        name,
        count: data.count,
        success_rate: data.success_rate
      })).sort((a, b) => b.count - a.count)
    }
    
    // 初始化图表
    nextTick(() => {
      initStatusChart()
      initSuccessRateChart()
    })
  } catch (error) {
    console.error('获取任务统计信息失败', error)
    ElMessage.error('获取任务统计信息失败')
  } finally {
    loading.stats = false
  }
}

// 获取最近执行的任务
const getRecentTasks = async () => {
  loading.recent = true
  try {
    const response = await requestUtil.get('tasks/task_result/', recentTasksQuery)
    recentTasks.value = response.results
    recentTasksTotal.value = response.count
  } catch (error) {
    console.error('获取最近任务失败', error)
    ElMessage.error('获取最近任务失败')
  } finally {
    loading.recent = false
  }
}

// 分页变化处理
const handleRecentTasksPageChange = (page) => {
  recentTasksQuery.page = page
  getRecentTasks()
}

// 每页数量变化处理
const handleRecentTasksSizeChange = (size) => {
  recentTasksQuery.page_size = size
  recentTasksQuery.page = 1
  getRecentTasks()
}

// 初始化任务状态分布图表
const initStatusChart = () => {
  if (!statusChartRef.value) return
  
  // 销毁旧图表
  if (statusChart) {
    statusChart.dispose()
  }
  
  statusChart = echarts.init(statusChartRef.value)
  
  const { status_counts } = taskStats.value
  if (!status_counts) return
  
  const option = {
    title: {
      text: '任务状态分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['成功', '失败', '进行中', '等待中', '取消', '重试']
    },
    series: [
      {
        name: '任务状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: status_counts.success || 0, name: '成功', itemStyle: { color: '#67c23a' } },
          { value: status_counts.failure || 0, name: '失败', itemStyle: { color: '#f56c6c' } },
          { value: status_counts.running || 0, name: '进行中', itemStyle: { color: '#e6a23c' } },
          { value: status_counts.pending || 0, name: '等待中', itemStyle: { color: '#909399' } },
          { value: status_counts.revoked || 0, name: '取消', itemStyle: { color: '#409eff' } },
          { value: status_counts.retry || 0, name: '重试', itemStyle: { color: '#9b59b6' } }
        ]
      }
    ]
  }
  
  statusChart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    statusChart && statusChart.resize()
  })
}

// 初始化成功率趋势图表
const initSuccessRateChart = () => {
  if (!successRateChartRef.value) return
  
  // 销毁旧图表
  if (successRateChart) {
    successRateChart.dispose()
  }
  
  successRateChart = echarts.init(successRateChartRef.value)
  
  const { time_stats } = taskStats.value
  if (!time_stats) return
  
  const option = {
    title: {
      text: '任务成功率趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['今日', '本周', '本月']
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '成功率',
        type: 'bar',
        data: [
          { 
            value: time_stats.today?.success_rate || 0, 
            itemStyle: { color: '#67c23a' }
          },
          { 
            value: time_stats.week?.success_rate || 0, 
            itemStyle: { color: '#409eff' }
          },
          { 
            value: time_stats.month?.success_rate || 0, 
            itemStyle: { color: '#909399' }
          }
        ],
        label: {
          show: true,
          position: 'top',
          formatter: '{c}%'
        }
      }
    ]
  }
  
  successRateChart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    successRateChart && successRateChart.resize()
  })
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'SUCCESS': 'success',
    'FAILURE': 'danger',
    'REVOKED': 'info',
    'STARTED': 'warning',
    'RETRY': 'warning',
    'PENDING': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取成功率状态
const getSuccessRateStatus = (rate) => {
  if (rate >= 90) return 'success'
  if (rate >= 70) return 'warning'
  return 'exception'
}

// 刷新数据
const refreshData = () => {
  getTaskStats()
  getRecentTasks()
}

// 查看所有结果
const viewAllResults = () => {
  router.push('/tasks/task_result')
}

// 查看任务详情
const viewTaskDetail = (id) => {
  router.push(`/tasks/task_result/detail/${id}`)
}

// 查看特定任务类型的结果
const viewTaskResults = (taskName) => {
  router.push({
    path: '/tasks/task_result',
    query: {
      search: taskName
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  getTaskStats()
  getRecentTasks()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-card {
  text-align: center;
  padding: 10px;
  margin-bottom: 20px;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-card.success .stat-value {
  color: #67c23a;
}

.stat-card.failure .stat-value {
  color: #f56c6c;
}

.stat-card.running .stat-value {
  color: #e6a23c;
}

.stat-card.pending .stat-value {
  color: #909399;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
</style>
